package com.jjwxc.jwjskandriod.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.AllStackViewHolder;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.AllStackRequest;
import com.jjwxc.jwjskandriod.model.BookAlsoListResponse;
import com.jjwxc.jwjskandriod.model.ChannelListResponse;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.jjwxc.jwjskandriod.widget.OptionalPop;
import com.jjwxc.jwjskandriod.widget.scroller.ConsecutiveScrollerLayout;

import java.util.ArrayList;
import java.util.List;

public class TabStackActivity extends BaseActivity {

    private String channels = "";
    private String word = "";
    private String sortType = "1";
    private String tag = "";

    private RecyclerView rv_space;
    private AllStackAdapter adapter;

    TabLayout tabLayoutOne;
    TabLayout tabLayoutTwo;
    TabLayout tabLayoutThree;

    private int page = 0;
    private LinearLayout ll_option;
    private ConsecutiveScrollerLayout ll_stack;
    private XRefreshView refreshView;
    public static long lastRefreshTime;
    private boolean isRefresh = true;
    AllStackRequest allStackRequest = new AllStackRequest();
    List<ChannelListResponse.DataBean> mData = new ArrayList<>();

    @Override
    public int getContentViewId() {
        return R.layout.activity_tabstack;
    }

    @Override
    public void findView() {
        ll_option = findViewById(R.id.ll_option);
        tabLayoutOne = findViewById(R.id.tab_allstack_one);
        tabLayoutTwo = findViewById(R.id.tab_allstack_two);
        tabLayoutThree = findViewById(R.id.tab_allstack_three);
        rv_space = findViewById(R.id.rv_allstack);
        ll_stack = findViewById(R.id.csl_stack);
        refreshView = findViewById(R.id.stack_view);
        rv_space.setNestedScrollingEnabled(false);
        rv_space.setFocusable(false);
        rv_space.setLayoutManager(new LinearLayoutManager(TabStackActivity.this));
        rv_space.addItemDecoration(new LinearLayouDecoration(TabStackActivity.this,
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));

    }

    @Override
    public void setListener() {
        tag = getIntent().getStringExtra("TAB_ID");
        String name = getIntent().getStringExtra("TAB_NAME");
        setTitle(name + "推荐书籍");
    }

    @Override
    public void afterCreate() {
        setTabOne(null);
        String[] TAB_TITLES = new String[]{"默认", "30万以下", "30-50万", "50-100万", "100万以上"};
        setTabsTwo(tabLayoutTwo, getLayoutInflater(), TAB_TITLES, 2);
        String[] TAB = new String[]{"累计热度", "销售量", "完结时间"};
        setTabsTwo(tabLayoutThree, getLayoutInflater(), TAB, 3);

        setClickListener();
    }


    public void setTabOne(String quan) {

        post(Url.listChannel, null, ChannelListResponse.class, new FFNetWorkCallBack<ChannelListResponse>() {
            @Override
            public void onSuccess(ChannelListResponse response) {
                if (response.getCode() == 200 && response.getData().size() > 0) {
                    mData.clear();
                    ChannelListResponse.DataBean bean = new ChannelListResponse.DataBean();
                    bean.setName("默认");
                    bean.setChannelId("");
                    mData.add(bean);
                    mData.addAll(response.getData());
                    setTabs(tabLayoutOne, getLayoutInflater(), mData);
                    afterCreate(0,quan);
                }
            }

            @Override
            public boolean onFail(ChannelListResponse response) {
                return false;
            }
        }, "{}");
    }

    public void setClickListener() {
        rv_space.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new AllStackAdapter(TabStackActivity.this);
        rv_space.setAdapter(adapter);
        refreshView.setPinnedTime(1000);
        refreshView.setMoveForHorizontal(true);
        refreshView.setPullRefreshEnable(true);
        refreshView.setPullLoadEnable(true);
        refreshView.setAutoLoadMore(true);
        refreshView.enableReleaseToLoadMore(true);
        refreshView.enableRecyclerViewPullUp(true);
        refreshView.enablePullUpWhenLoadCompleted(true);
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);

        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                page = 0;
                afterCreate(page,null);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page += 1;
                afterCreate(page * 10,null);
            }
        });


        //筛选项
        ll_option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new OptionalPop().optionalPopWindow(v, TabStackActivity.this, allStackRequest, new OptionalPop.PopOptionalListener() {
                    @Override
                    public void onValueClick(AllStackRequest value) {
                        isRefresh = false;
                        allStackRequest = value;
                        if (value.getChannels() != null && value.getChannels().size() > 0) {
                            channels = value.getChannels().get(0);
                        }else{
                            channels ="";
                        }
                        if (!StUtils.isEmpty(value.getWordSize())) {
                            word = value.getWordSize();
                        }else{
                            word ="";
                        }
                        if (!StUtils.isEmpty(value.getSortType())) {
                            sortType = value.getSortType();
                        }else{
                            sortType="1";
                        }
                        String s = value.getWordSize();
                        if (StUtils.isEmpty(s)) {
                            tabLayoutTwo.getTabAt(0).select();
                        } else {
                            tabLayoutTwo.getTabAt(Integer.parseInt(s)).select();
                        }
                        String rs = value.getReadingStatus();
                        if (StUtils.isEmpty(rs)) {
                            tabLayoutThree.getTabAt(0).select();
                        } else {
                            tabLayoutThree.getTabAt(Integer.parseInt(rs)).select();
                        }
                        int selectOne = 0;
                        if (value.getChannels().size() > 0) {
                            for (int i = 0; i < mData.size(); i++) {
                                if (mData.get(i).getChannelId().equals(value.getChannels().get(0))) {
                                    selectOne = i;
                                }
                            }
                        }
                        tabLayoutOne.getTabAt(selectOne).select();
                        if (!isRefresh) {
                            afterCreate(0,"");
                            isRefresh = true;
                        }
                    }
                });
            }
        });
    }

    public void afterCreate(int page,String quan) {
        if (!StUtils.isEmpty(channels)) {
            List<String> channerl = new ArrayList<>();
            channerl.add(channels);
            allStackRequest.setChannels(channerl);
        }else{
            allStackRequest.setChannels(null);
        }
        allStackRequest.setLimit(10);
        allStackRequest.setOffset(page);
        allStackRequest.setWordSize(word);
        if (!StUtils.isEmpty(tag)) {
            List<String> tagIds = new ArrayList<>();
            tagIds.add(tag);
            allStackRequest.setTagIds(tagIds);
        }else{
            allStackRequest.setTagIds(null);
        }
        allStackRequest.setSortType(sortType);
        //开始网络请求
        getListBook(allStackRequest,quan);

    }

    public void getListBook(AllStackRequest allStackRequest,String quan) {
        post(Url.listUserInterestBook, quan, BookAlsoListResponse.class, new FFNetWorkCallBack<BookAlsoListResponse>() {
            @Override
            public void onSuccess(BookAlsoListResponse response) {
                lastRefreshTime = refreshView.getLastRefreshTime();
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() <= 0) {
                        refreshView.setLoadComplete(true);
                    }
                    if (page == 0) {
                        refreshView.stopRefresh();
                        refreshView.setLoadComplete(false);
                        adapter.setData(response.getData());
                    } else {
                        refreshView.stopLoadMore();
                        adapter.addData(response.getData());
                    }
                }

            }

            @Override
            public boolean onFail(BookAlsoListResponse response) {
                return false;
            }
        }, JSON.toJSONString(allStackRequest));
    }

    /**
     * 设置页卡显示效果2
     */
    private void setTabsTwo(TabLayout tabLayout, LayoutInflater inflater, String[] list, int page) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allstack_item_tab, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_allstack_tab);
            tvTitle.setText(list[i]);
            tabLayout.addTab(tab);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isRefresh) {
                    if (page == 2) {
                        if (tab.getPosition() == 0) {
                            word = "";
                        } else {
                            word = tab.getPosition() + "";
                        }
                    } else {
                        sortType = (tab.getPosition() + 1) + "";
                    }
                    afterCreate(0,"");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    /**
     * 设置页卡显示效果
     *
     * @param tabLayout
     * @param inflater
     */
    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, List<ChannelListResponse.DataBean> list) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.size(); i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allstack_item_tab, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_allstack_tab);
            tvTitle.setText(list.get(i).getName());
            tabLayout.addTab(tab);

        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isRefresh) {
                    channels = list.get(tab.getPosition()).getChannelId();
                    afterCreate(0,"");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //最后再给刷新的权限
        isRefresh = true;
    }

    public class AllStackAdapter extends BaseRecyclerAdapter<AllStackViewHolder> {
        private Context context;


        private List<BookAlsoListResponse.DataBean> mData = new ArrayList<>();


        public AllStackAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<BookAlsoListResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<BookAlsoListResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public AllStackViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.allstack_item_list, parent, false);
            AllStackViewHolder viewHolder_text = new AllStackViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public AllStackViewHolder getViewHolder(View view) {
            return new AllStackViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
        @Override
        public void onBindViewHolder(final AllStackViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            FFImageLoader.loadImage(context, holder.img_allstack_item, mData.get(position).getCoverImgUrl() + "", mData.get(position).getBookId(), true);
            holder.tv_bookname_allstack.setText(mData.get(position).getName());
            holder.tv_book_author.setText(mData.get(position).getAuthor());
            holder.tv_book_info.setText(StUtils.reBlank(mData.get(position).getBookIntro()));
            holder.tv_allstack_tab.setText(mData.get(position).getChannlname());
            holder.cl_allstack_list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(TabStackActivity.this, BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);
                }
            });


        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }
}
